<!-- 培训会议课程管理-->
<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row  class="query-form">
                <Col span="8">
                    <FormItem label="所属单位：">
                        <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId"
                                     :rootOrgId="companyId" :orgTree="true"></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="课程名称：">
                        <Input class='query-form-el' type='text' v-model='dataToQuery.courseName'/>
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label="课程分类：">
                        <Select v-model='dataToQuery.courseClassification'>
                            <Option v-for="item in courseClassificationMap" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row v-if="switchFlag" class="query-form">
                <Col span="8" :offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
               :loading='pageStatus.loading'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="getModalTitle('课程管理')" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800
               :styles="{height:'559px'}"  class-name='limit-height-dialog' @on-cancel="onCancel">
            <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'"
                  :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?130:null">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label='所属单位：' prop='staffOrgId'>
                            <div v-if="mode === 'view'">{{dataToView.staffOrgName}}</div>
                            <cascader-dom v-else ref='orgCascader' @setOrgInfo='setStaffOrgId' @setOrgname="setStaffOrgName" :orgTree="true" :currentOrgId = "dataToView.staffOrgId"
                                          :rootOrgId="companyId" :setCurrentName="{label:dataToView.staffOrgName,value:dataToView.staffOrgId}" ></cascader-dom>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label='课程名称：' prop='courseName'>
                            <div v-if="mode === 'view'">{{ dataToView.courseName }}</div>
                            <Input v-else class='query-form-el' placeholder="请填写课程名称" type='text' v-model='dataToView.courseName'></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label='课程分类 ：' prop='courseClassification'>
                            <div v-if="mode === 'view'">{{ this.courseClassificationMap[dataToView.courseClassification] && this.courseClassificationMap[dataToView.courseClassification].codingName }}</div>
                            <Select v-else v-model='dataToView.courseClassification' class='query-form-el'>
                                <Option v-for="item in courseClassificationMap" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label='课时数：' prop='courseNum'>
                            <div v-if="mode === 'view'">{{ dataToView.courseNum }}</div>
                            <InputNumber v-else class='query-form-el' placeholder="请填写课时数" :min="0" type='text' v-model='dataToView.courseNum'></InputNumber>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label='课程排序：' prop='courseRanking'>
                            <div v-if="mode === 'view'">{{ dataToView.courseRanking }}</div>
                            <InputNumber v-else class='query-form-el' placeholder="请填写课程排序(数字越大排序越靠前)" :min="0" type='text' v-model='dataToView.courseRanking'></InputNumber>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label='课程简介：' prop='courseIntroduction'>
                            <div v-if="mode === 'view'">{{ dataToView.courseIntroduction }}</div>
                            <Input v-else class='query-form-el' placeholder="请填写课程简介" type='textarea' :autosize="{minRows:2,maxRows:5}" v-model='dataToView.courseIntroduction'></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around">
                    <Col span="23">
                        <FormItem label="上传课程封面图片：" prop="uploadList">
                            <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                                <img :src="item.picture">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.id)"></Icon>
                                    <!--<Icon type="ios-trash-outline" v-if="mode === 'view'"></Icon>-->
                                    <Icon type="ios-trash-outline" v-if="mode != 'view'" @click.native="remove(item.id)"></Icon>
                                </div>
                            </div>
                            <Upload v-show="mode != 'view'"
                                    ref="upload"
                                    :show-upload-list="false"
                                    :format="['jpg','jpeg','png','gif']"
                                    accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                    :max-size="512"
                                    :before-upload="handleBeforeUpload"
                                    type="drag"
                                    :action="uploadPTWFiles"
                                    :disabled="mode === 'view'"
                                    style="display: inline-block;width:58px;">
                                <div style="width: 58px;height:58px;line-height: 58px;">
                                    <Icon type="ios-camera" size="20"></Icon>
                                </div>
                            </Upload>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around">
                    <Col span="23">
                        <FormItem v-if="mode === 'view'" label="课程附件：">
                            <div v-show="courseVideo.length>0" v-for="item in courseVideo">
                                <a @click="downloadFile(item)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                            </div>
                        </FormItem>
                        <FormItem v-else label="上传课程附件：" prop="courseAttachment">
                            <div >
                                <Upload ref="upload"
                                        :before-upload="courseAttachmentUpload"
                                        :show-upload-list="false"
                                        type="drag"
                                        :action="fileUrl">
                                    <div style="padding: 20px">
                                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                        <p>点击将文件拖拽到这里上传</p>
                                        <span style="font-size:8px;color: #797a64">只能上传一个视频类型的文件</span>
                                    </div>
                                </Upload>
                            </div>
                            <div v-show="courseVideo.length>0" v-for="item in courseVideo">
                                <a @click.prevent="downloadFile(item)">{{item.fileName}}</a>
                                <Button type="text" icon="md-trash" @click="videoRemove(item)"
                                        style="margin-left: 20px;margin-bottom: 3px"/>
                            </div>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label='创建人：' prop='createUserName'>
                            <div v-if="mode === 'view'">{{ dataToView.userName }}</div>
                            <Input v-else readonly class='query-form-el'  type='text' v-model='dataToView.userName'></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">

                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定
                </Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="onCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>
    import {Api} from '../../../api/index.js'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import pageCommonFunction from '@/components/pageCommonFunction.js'

    export default {
        components: {cascaderDom},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                    {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'staffOrgName',minWidth: 200,title: '所属单位',  align: 'center' },
                    { key:'courseName',minWidth: 150,title: '课程名称',  align: 'center',tooltip:true },
                    { key:'courseNum',minWidth: 100,title: '课时数',  align: 'center'},
                    { key:'courseClassification',minWidth: 150,title: '课程分类 ',  align: 'center',render:(h, params)=>{
                            return h('span', this.courseClassificationMap && this.courseClassificationMap[params.row.courseClassification] && this.courseClassificationMap[params.row.courseClassification].codingName)
                        }, },
                    { key:'courseRanking',minWidth: 100,title: '课程排序',  align: 'center' },
                    { key:'courseIntroduction',minWidth: 200,title: '课程简介',  align: 'center' ,tooltip:true},
                    { key:'viewNumber',minWidth: 100,title: '浏览数',  align: 'center' },
                    { key:'likes',minWidth: 100,title: '点赞数',  align: 'center' },
                    { key:'userName',minWidth: 100,title: '创建人',  align: 'center' },
                    { key:'createDate',minWidth: 100,title: '创建时间',  align: 'center',render: this.renderCellDate },
                    { key:'updateDate',minWidth: 110,title: '最后修改时间',  align: 'center',render: this.renderCellDate },
                    this.getActionColumns()
                ],
                ruleCustom: {
                    staffOrgId: [ { required: true, message: '请选择所属单位', trigger: 'change'}],
                    courseName: [ { required: true, message: '请填写课程名称', trigger: 'change',}],
                    courseNum: [ { required: true, message: '请填写课时数', trigger: 'change',type: 'number'}],
                    courseClassification: [ { required: true, message: '请填写课程分类 ', trigger: 'change',}],
                    courseRanking: [ { required: true, message: '请填写课程排序', trigger: 'change',type: 'number'}],
                    courseIntroduction: [ { required: true, message: '请填写培训内容', trigger: 'change',}],
                    uploadList:[{
                        validator:(rule, value, callback) =>{
                            if(this.uploadList == undefined || this.uploadList.length == 0 || this.uploadList.length >9){
                                callback(' ')
                            }else{
                                callback()
                            }
                        },
                        required: true,
                        message: '请上传附件',
                        trigger: 'change'
                    }],
                    courseAttachment:[{
                        validator:(rule, value, callback) =>{
                            if(this.courseVideo == undefined || this.courseVideo.length == 0){
                                callback(' ')
                            }else{
                                callback()
                            }
                        },
                        required: true,
                        message: '请上传附件',
                        trigger: 'change'
                    }],
                },
                tableHeight: 10,
                companyId:'',
                idFiles:[],
                courseClassificationMap:{},
                evaluationMethodMap:{},
                trainingTypesMap:{},
                // api
                queryUrl: Api.queryCourseManagement,
                deleteUrl: Api.deleteCourseManagement,
                updateUrl: Api.updateCourseManagement,
                saveUrl: Api.saveCourseManagement,

                uploadList: [],
                viewUrl : Api.interestedPartiesUserFile,
                courseVideo:[],
                videoUrl:Api.courseVideoUrl.indexOf("210.12.194.89")>0?Api.courseVideoUrl.replace('/uploadToSystem',''):Api.courseVideoUrl,
                _courseAttachment:null
            }
        },
        async mounted() {
            await this.$http.get(Api.queryCodeDetailBySortId + '/TRA-000007', {params: {}}).then((res) => {
                this.courseClassificationMap = this.dictListToMap(res.data.data);
            });
            this.companyId=sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                if (this.dataToQuery.companyId != null&&this.dataToQuery.companyId != undefined&&this.dataToQuery.companyId != '') {
                    this.dataToQuery.orgId=this.dataToQuery.companyId
                }else {
                    this.dataToQuery.orgId = sessionStorage('userId').getObject('userId').companyId
                }
                this.queryAjax();
            },

            submit(name) {
                this.submitAjax(name);
                if (this.dataToView._courseAttachment != this.dataToView.courseAttachment) {
                    this.videoRemove1(this.dataToView._courseAttachment);
                }
            },
            /*async beforeEditDialogOpen(data) {
                data.row.resWorks=data.row.resWork.split(',')
            },*/

            handleView (id) {
                let routeUrl = this.$router.resolve({
                    path: "/imgDetails",
                    query: {id:id}
                });
                window.open(routeUrl.href, '_blank');
            },
            remove(id) {
                console.log(id)
                let url = this.viewUrl + '/file/' + id;
                this.$http.delete(url).then((res) => {
                    this.getCoursePic(this.dataToView.id)
                })
            },
            handleBeforeUpload (file) {
                if(file.size > 1024*512){
                    this.$Message.error('图片不能大于512kb.');
                    return false;
                }
                let index = file.name.lastIndexOf(".");
                let suffix = file.name.substr(index+1);
                if(suffix!='jpg' && suffix!='jpeg' && suffix!='png'&& suffix!='gif'){
                    this.$Message.error("请上传jpg,jpeg,png,gif格式的图片");
                    return false;
                }
                let check = this.uploadList.length < 9;
                if (!check) {
                    this.$Message.error('最多上传9张图片');
                    return false;
                }
                let formData = new FormData();
                formData.append("files", file);
                this.$http.post(this.viewUrl +  '/' + this.dataToView.id + '/files/picture/coursePic', formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.success("上传成功");
                        this.getCoursePic(this.dataToView.id)
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                }).catch(e => {
                    console.log(e);
                    this.$Message.error("数据获取失败");
                })
                return false;
            },
            getCoursePic(id){
                let url=this.viewUrl +  '/' + id + '/files/picture'
                this.$http.get(url + "?field=coursePic").then((res) => {
                    if (res.data.result == "success") {
                        console.log(res.data)
                        this.uploadList = res.data.data
                    }
                })
            },
            createEmptyDataToAdd() {
                this.uploadList=[]
                this.courseVideo=[]
                return {
                    id:this.get_uuid(),
                    courseAttachment:null,
                    staffOrgName:sessionStorage('userId').getObject('userId').companyName,
                    staffOrgId:sessionStorage('userId').getObject('userId').companyId,
                    userName:sessionStorage('userId').getObject('userId').userName,
                    createUserId: sessionStorage('userId').getObject('userId').userId,
                    courseNum:0,//课时数
                    viewNumber:0,//浏览数
                    likes:0,//点赞数
                    courseRanking:0//课程排序(越大排序越靠前)
                }
            },
            async afterDataToViewInit() {
                this.courseVideo=[]
                await this.getCoursePic(this.dataToView.id);
                this.dataToView._courseAttachment=this.dataToView.courseAttachment;
                this.courseVideo.push({
                    filePath:this.dataToView.courseAttachment,
                    fileName:this.dataToView.courseAttachment.substr(this.dataToView.courseAttachment.lastIndexOf("/")+1,this.dataToView.courseAttachment.length
                    )})
            },
            videoRemove(item){
                if (this.dataToView._courseAttachment != this.dataToView.courseAttachment) {
                    this.videoRemove1(this.dataToView.courseAttachment);
                }
                this.courseVideo=[]
                this.dataToView.courseAttachment=null
            },
            onCancel(){
                if (this.mode == 'add') {
                    this.videoRemove1(this.dataToView.courseAttachment);
                }
                if (this.dataToView._courseAttachment != this.dataToView.courseAttachment) {
                    this.videoRemove1(this.dataToView.courseAttachment);
                }
                this.dialogShow=false;
                this.dataToView={};
            },
            downloadFile(item){
                let url = this.videoUrl +'/downLoadwVideo?filePath='+item.filePath;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = item.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            videoRemove1(id) {
                console.log(id)
                let url = this.videoUrl +'/deleteVideo?filePath='+id;
                this.$http.post(url).then((res) => {
                    if (res.data.result == "success") {
                    } else {
                    }
                })
            },
            courseAttachmentUpload (file) {
                if ( this.courseVideo.length == 1) {
                    this.$Message.error('只能上传一个视频文件');
                    return false;
                }
                let formData = new FormData();
                formData.append("uploadFile", file);
                this.$http.post(this.videoUrl+'/video', formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.success("上传成功");
                        this.dataToView.courseAttachment=res.data.filePath
                        this.courseVideo.push({
                            filePath:this.dataToView.courseAttachment,
                            fileName:this.dataToView.courseAttachment.substr(this.dataToView.courseAttachment.lastIndexOf("/")+1,this.dataToView.courseAttachment.length
                            )})
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                }).catch(e => {
                    console.log(e);
                    this.$Message.error("数据获取失败");
                })
                return false;
            },

            setOrgId(data) {
                this.dataToQuery.companyId = data[data.length - 1];
            },
            setStaffOrgId(data) {
                this.dataToView.staffOrgId = data[data.length - 1];
            },
            setStaffOrgName(data) {
                this.dataToView.staffOrgName = data
            },
        },

    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
